package com.quarkus.resource;

import com.quarkus.entity.users.User;
import io.quarkus.hibernate.orm.PersistenceUnit;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * @Author: TongRui乀
 * @Date: 2021/3/21 15:08
 * @description：
 */
@Path("user")
public class UserResource {

    @Inject
    @PersistenceUnit("user")
    EntityManager entityManager;

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Object getUserById(@PathParam("id") Integer id){
        return entityManager.createNativeQuery("select * from t_user where id = ?").setParameter(1,id)
                .getSingleResult();
    }


    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Transactional
    public int save(User user){
        entityManager.persist(user);
        return 1;
    }

    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Transactional
    public User update(User user){

        var u = entityManager.find(User.class, user.getId());

        u.setName(u.getName()+"_UPDATE");

        return u;
    }


    @DELETE
    @Consumes(MediaType.APPLICATION_JSON)
    @Transactional
    public User delete(User user){

        var u = entityManager.getReference(User.class, user.getId());

        entityManager.remove(u);

        return u;
    }

}
